package com.mec.web.y2012.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONObject;

/**
 * Servlet implementation class JSONExampleServlet
 */
@WebServlet("/ajax/JSONExample")
public class JSONExampleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public JSONExampleServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String json = AjaxUtil.readStringFromRequest(request);
		//
		JSONObject jsonObject = null;
		
		try{
			jsonObject = new JSONObject(json);
		
			//
			String responseText = "You have a " + jsonObject.getInt("year") +
					" " + jsonObject.getString("make") + " " + jsonObject.getString("model") 
					+ " tha is " + jsonObject.getString("color") + " in color";
			
			response.setContentType("text/xml");
			response.getWriter().print(responseText);
		}catch(Exception pe){
			logger.error("ParseException: ", pe);
		}
	}
	
	
	/*private void readJSONStringFromRequestBody(HttpServletRequest request){
		StringBuffer json = new StringBuffer();
		//
		String line = null;
		try{
			BufferedReader reader = request.getReader();
			while(null != (line = reader.readLine())){
				json.append(line);
			}
		}catch(Exception e){
			logger.error("Error reading JSON String:", e);
		}
	}*/
	private static final Logger logger = 
			Logger.getLogger(JSONExampleServlet.class);

}
